
public class BinaryTree {
    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;
        

        public TreeNode(char val) {
            this.val = val;
        }
    }

    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        //E.right = H;
        return A;
    }

    /**
     * 获取叶子节点的个数-遍历思路
     */
    public int leafCount;
    public void getLeafNodeCount(TreeNode root) {
        if (root == null) return;
        if (root.right == null && root.left == null) {
            leafCount++;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }

    /**
     * 获取叶子节点的个数-子问题思路
     */
    public int getLeafNodeCount2(TreeNode root) {
        if (root == null) return 0;
        if (root.right == null && root.left == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
    }

    public static void main(String[] args) {
        BinaryTree binaryTree = new BinaryTree();
        BinaryTree.TreeNode root = binaryTree.createTree();

        System.out.println("叶子节点的个数：");
        binaryTree.getLeafNodeCount(root);
        System.out.println(binaryTree.leafCount);

        System.out.println("叶子节点的个数2：");
        System.out.println(binaryTree.getLeafNodeCount2(root));

    }
}
